import React, {
    Component,
} from 'react';

import {
    StyleSheet,
    Text,
    View,
    Platform,
    FlatList,
    Dimensions,
    TouchableOpacity,
    Image,
    ScrollView,
    StatusBar,
    Linking,
    ActivityIndicator,
    DeviceEventEmitter,
    TextInput,
} from 'react-native';

import AndroidModule from 'src/utils/AndroidConnent'
import Constant from '../../utils/Constant'//全局变量
import HttpUtils from "../../utils/HttpUtils";
import HttpUrls from "../../utils/HttpUrls";
import Header from "../../components/header";
import { ToastToUser } from '../../utils/CustomToast';
import Loading from "../../utils/Loading";
import { WeChatPay, alipay } from '../../utils/WeChatUtils'


const screenW = Dimensions.get('window').width;
const isIos = Platform.OS == 'ios';

let navigation = null

/**
 * 确认支付
 */
export default class ConfirmPayPage extends Component {

    constructor(props) {
        super(props);
        let payData = this.props.route.params && this.props.route.params.payData ? this.props.route.params.payData : {}//余额充值
        this.state = {
            payType: '1',
            availAmount: 0,
            payData,
            cashRecharge: payData.cashRecharge ? true:false,
            hideCashPay: payData.hideCashPay ? true : false,
        }
    }

    componentDidMount() {
        this.requestavailAmount()
    }

    orderPay() {
        let params = {
            goodsId: this.state.payData.goodsId,
            orderType: this.state.payData.orderType,
            buyerUserId: Constant.userInfo.userId,
            operator: Constant.userInfo.userId,
            payChannel: this.state.payType,
            buyerMerchantId: Constant.userInfo.merchantId
        }
        this.Loading.show()
        HttpUtils.postRequest(HttpUrls.createOrder, params)
            .then((result) => {

                if (result.success) {
                    let data = result.data
                    let orderNo = data.orderNo
                    this.paySubmit(orderNo)

                } else {
                    if (this.Loading) {
                        this.Loading.hide();
                    }
                    ToastToUser(result.msg)
                }

            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

    paySubmit(orderNo) {
        let param = {
            userId: Constant.userInfo.userId,
            merchantId: Constant.userInfo.merchantId,
            totalAmount: this.state.payData.totalAmount,
            payChannel: parseInt(this.state.payType),
            bizOrderId: this.state.payData.orderId, //------------业务订单id
            outTradeNo: orderNo ? orderNo:this.state.payData.orderNo, //------------业务订单号
            orderBody: this.state.payData.goodsName,
            orderSubject: this.state.payData.goodsDesc,
            tradeType: this.state.payData.tradeType
        }

        if (this.Loading) {
            this.Loading.show()
        }
        HttpUtils.postRequest(HttpUrls.paymentOrderGenerate, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                let code = result.code
                if (code == 0) {
                    if (this.state.payType == '1') {
                        let alipayAppPreProcesResponseRO = result.data.alipayAppPreProcesResponseRO
                        let orderString = alipayAppPreProcesResponseRO.orderString
                        if (this.Loading) {
                            this.Loading.show() 
                        }
                        console.log('orderString = ',orderString)
                        alipay(orderString).then((code) => {
                            if (this.Loading) {
                                this.Loading.hide() 
                            }
                            if (code != 0) {
                                ToastToUser('支付失败')
                                this.props.payResult(false);
                            } else {
                                // this.timer1 = setInterval(() => {
                                //     this.confirmOutTradeNo();
                                // }, 1000);
                            }
                        })
                    } else if (this.state.payType == '2') {
                        let wxPreOrderResult = result.data.wxPreOrderResult
                        WeChatPay(wxPreOrderResult)
                    } else {
                        ToastToUser('支付成功')
                    }
                } else {
                    ToastToUser(result.msg + '')
                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
            });
    }

    render() {
        navigation = this.props.navigation
        return (
            <View style={styles.container}>

                <Header navigation={navigation} Title={'确认付款'} hideSepLine={true} />

                <View style={styles.payMoneyContain}>
                    <View style={{ alignItems: 'center' }}>
                        <Text style={styles.priceTagText}>￥<Text style={{ fontSize: 40 }}>{(this.state.payData.totalAmount / 100).toFixed(2)}</Text></Text>
                        <Text style={styles.moneyDesText}>{this.state.payData.title}</Text>
                    </View>
                </View>

                <View style={styles.paySelectContain}>
                    <Text style={styles.titleText}>请选择支付方式</Text>

                    <TouchableOpacity style={styles.itemContain2}
                        onPress={() => {
                            this.setState({
                                payType: '1'
                            })
                        }}>
                        <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                            <Image style={styles.payImg} source={require('source/image/pay/ali_pay.png')} ></Image>
                            <Text style={styles.reasonTitle}>支付宝</Text>
                        </View>

                        <Image style={styles.checkImg} source={this.state.payType == '1' ? require('source/image/pay/pay_select.png') : require('source/image/pay/pay_unselect.png')}></Image>
                    </TouchableOpacity>

                    <TouchableOpacity style={styles.itemContain2}
                        onPress={() => {
                            this.setState({
                                payType: '2'
                            })
                        }}>
                        <View style={{ flexDirection: 'row', alignItems: 'center' }}>
                            <Image style={styles.payImg} source={require('source/image/pay/wechat_pay.png')} ></Image>
                            <Text style={styles.reasonTitle}>微信</Text>
                        </View>

                        <Image style={styles.checkImg} source={this.state.payType == '2' ? require('source/image/pay/pay_select.png') : require('source/image/pay/pay_unselect.png')}></Image>
                    </TouchableOpacity>
                    {
                        !this.state.hideCashPay ?
                            <TouchableOpacity style={styles.itemContain2}
                                onPress={() => {
                                    if (this.state.payData.totalAmount > this.state.availAmount) {
                                        ToastToUser('余额不足')
                                    } else {
                                        this.setState({
                                            payType: '3'
                                        })
                                    }
                                }}>
                                <View style={{ flexDirection: 'row', alignItems: 'center', flex: 1 }}>
                                    <Image style={styles.payImg} source={require('source/image/pay/cash_pay.png')} ></Image>
                                    <Text style={styles.reasonTitle}>余额支付</Text>
                                    <Text style={{ flex: 1, textAlign: 'right', fontSize: 14, color: '#CCCCCC', marginRight: 10 }}>可用余额：{this.state.availAmount}</Text>
                                </View>

                                <Image style={styles.checkImg} source={this.state.payType == '3' ? require('source/image/pay/pay_select.png') : require('source/image/pay/pay_unselect.png')}></Image>
                            </TouchableOpacity>
                            :
                            null
                    }
                </View>

                <View style={{ flex: 1 }}></View>

                <TouchableOpacity style={[styles.payBtnStyle, { marginBottom: Constant.isIPhoneX ? 34 : 20 }]}
                    onPress={() => {
                        if (this.state.cashRecharge) {
                            this.paySubmit()
                        } else {
                            this.orderPay()
                        }
                        
                    }}>
                    <Text style={styles.payBtnText}>立即支付</Text>
                </TouchableOpacity>

                <Loading onRef={(ref) => (this.Loading = ref)} />

            </View>
        );
    }

    requestavailAmount() {
        HttpUtils.getRequest(HttpUrls.merchantAccountDetail, { merchantId: Constant.userInfo.merchantId })
            .then((result) => {
                let code = result.code
                if (code == 0) {
                    let data = result.data
                    this.setState({
                        availAmount: data.availAmount ? (data.availAmount / 100).toFixed(2) : 0,
                    })
                }
            })
            .catch((error) => {

            });
    }

}

const styles = StyleSheet.create({
    container: {
        width: screenW,
        height: '100%',
        flexDirection: 'column',
        backgroundColor: '#f9f9f9'

    },
    payMoneyContain: {
        justifyContent: 'center',
        alignItems: 'center',
        height: 120
    },
    priceTagText: {
        fontSize: 20,
        color: '#222222',
        fontWeight: 'bold'
    },
    moneyDesText: {
        fontSize: 14,
        color: '#666666',
        marginTop: 6
    },

    paySelectContain: {
        marginLeft: 16,
        marginRight: 16,
        backgroundColor: '#ffffff',
        borderRadius: 8,
        marginTop: 20,
        paddingLeft: 12,
        paddingRight: 12
    },
    titleText: {
        fontSize: 16,
        color: '#222222',
        marginTop: 16,
        fontWeight: '500'
    },
    itemContain2: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        height: 54,

    },
    checkImg: {
        width: 20,
        height: 20
    },

    reasonTitle: {
        fontSize: 16,
        color: '#333333',

    },

    payImg: {
        width: 22,
        height: 22,
        marginRight: 10
    },
    payBtnStyle: {
        marginLeft: 16,
        marginRight: 16,
        backgroundColor: '#FFE000',
        justifyContent: 'center',
        alignItems: 'center',
        height: 46,
        borderRadius: 23,
        marginBottom: 20
    },
    payBtnText: {
        fontSize: 15,
        color: '#222222',
        fontWeight: '500'
    }

})